/**
 * Created by wei on 16-8-24.
 * 工程量变更
 * 新增图片需求
 * 缓存的图片需要funId， 我根据每一个变更的索引+1，来做funId
 */
angular.module("task.qutyChangeController", ["starter.taskService", "starter.taskDirective"])
  // 工程量变更Ctrl
  .controller("QutyChangeCtrl", function ($scope,$state,$rootScope,$task, $stateParams, $user, $dfHttp, $imageUploadCache, $loading, $log, $cordovaDialogs, $ionicPopup, $ionicHistory, $interval, $cordovaFile, $dfUtil, $timeout) {
    $scope.project = $stateParams.args.project;
    $scope.entry = $stateParams.args.entry;
    var imagesClass = [];
    var flag = false;
    var checkImageId = 0;

    var user = $user.getCurrentUserSync();

    /**
     * 构造工程量变更的对象
     * @returns {{changeText: string, engineerId: string, engineering: string, projectId: number}}
     */
    function getQutyChangeObj() {
      return {
        changeText: "",
        engineerId: "",
        engineering: "",
        engineerStatus: "",
        projectId: $scope.project.projectId
      }
    }

    // 从服务器获取数据
    getEngineerChange(user.userId, $scope.project.projectId);

    /**
     * 从服务器获取数据
     * @param userId
     * @param projectId
     */
    function getEngineerChange(userId, projectId) {
      $loading.show("获取工程量信息中...");
      $dfHttp.get("api/others/getEngineerChange.json", {
        userId: userId,
        projectId: projectId
      }).success(function (data) {
        if (data.code == "SUCCESS"){
          $loading.hide();
          $scope.spmsEngineerChangeList = data.data.enginnerChangeList;

          if (!angular.isArray($scope.spmsEngineerChangeList)){
            $scope.spmsEngineerChangeList = [];
          }

          // 判断数组的长度，如果为0，则默认添加一组空白数据
          if ($scope.spmsEngineerChangeList.length == 0){
            var qutyChangeObj = getQutyChangeObj();
            qutyChangeObj.imageId = 1;
            $scope.spmsEngineerChangeList.push(qutyChangeObj);
          } else{
            angular.forEach($scope.spmsEngineerChangeList, function(obj, index){
              obj.engineerStatus = $scope.project.engineerStatus;
              obj.imageId = index+1;
              obj.GLBG = data.data.classList[index].length > 0 ? "HAS_IMAGE" : "";
              imagesClass.push(data.data.classList[index]);
            });
          }
        } else{
          $loading.showError("获取数据失败，请稍后再试");
          $ionicHistory.goBack();
        }
      }).error(function (e) {
        $loading.showError("服务器有点小问题，请稍后再试");
        $ionicHistory.goBack();
      });
    }

    //项目日志
    $scope.forwardProjectLog = function (project) {
      $state.go('tab.project-log',{args:project});
    }

    /**
     * 添加工程内容
     */
    $scope.add = function () {
      $cordovaDialogs.confirm("确认添加？","添加变更记录",["取消","添加"]).then(function (buttonIndex) {
        if (buttonIndex == 2){
          var qutyChangeObj = getQutyChangeObj();
          if ($scope.spmsEngineerChangeList.length == 0){
            qutyChangeObj.imageId = 1;
          } else{
            qutyChangeObj.imageId = $scope.spmsEngineerChangeList[$scope.spmsEngineerChangeList.length - 1].imageId+1;
          }
          $scope.spmsEngineerChangeList.push(qutyChangeObj);
        }
      });
    }

    /**
     * 删除工程内容
     * @param index
     */
    $scope.del = function (index) {
      $cordovaDialogs.confirm("确认删除？","删除变更记录",["取消","删除"]).then(function (buttonIndex) {
        if (buttonIndex == 2){
          $scope.spmsEngineerChangeList.splice(index, 1);
        }
      });
    }

    /**
     * 提交
     */
    $scope.submit = function () {
      $cordovaDialogs.confirm("确认保存？","保存变更记录",["取消","保存"]).then(function (buttonIndex) {
        if (buttonIndex == 2){
          if ($scope.spmsEngineerChangeList.length != 0 && angular.isArray($scope.spmsEngineerChangeList)){ // 判断list中存在的个数，如果不为0，则提交
            if (hasNull($scope.spmsEngineerChangeList)){
              $loading.showError("变更内容和工程量不能为空");
            } else{
              submit(user.userId, $scope.project.projectId, $scope.spmsEngineerChangeList);
            }
          } else{
            $cordovaDialogs.alert("请先添加变更记录");
          }
        }
      })

      /**
       * 检查字段是否含空
       * @param spmsEngineerChangeList
       * @returns {boolean}
       */
      function hasNull(spmsEngineerChangeList) {
        var flag = false;
        for (var i in spmsEngineerChangeList){
          if (spmsEngineerChangeList[i].changeText == "" || spmsEngineerChangeList[i].engineering == ""){
            flag = true;
            break;
          }
        }

        return flag;
      }
    }

    /**
     * 提交
     * @param userId
     * @param projectId
     * @param spmsEngineerChangeList
     */
    function submit(userId, projectId, spmsEngineerChangeList) {
      $loading.show("提交中...");
      $dfHttp.post("api/others/saveEngineerChange.json", {
        userId: userId,
        projectId: projectId,
        spmsEngineerChangeList: spmsEngineerChangeList
      }).success(function (data) {
        if (data.code == "SUCCESS"){
          $loading.showSuccess("保存成功！");

          var i = 0;
          angular.forEach($scope.spmsEngineerChangeList, function (obj, index) {
            var imageCache = $imageUploadCache.getImagesByParams(obj.imageId, "GCLBG", "GLBG");
            if (imageCache.images){
              if (imageCache.images.length > 0){
                i++;
              }
            }
          })

          if (i > 0){
            angular.forEach(data.data, function (obj, index) {
              obj.imageId = index+1;
            })
            imageUpload(data.data);
          }

          $ionicHistory.goBack();
          $task.getCountOfTasks(user.userId);
          $rootScope.listStatus = "ON_GOING";
          // imageUpload(spmsEngineerChangeList);
          // $ionicHistory.goBack();
          // $task.getCountOfTasks(user.userId);
          // $rootScope.listStatus = "ON_GOING";
        } else{
          $loading.showError("保存失败！");
        }
      }).error(function (e) {
        $loading.showError("服务器有点小问题，请稍后再试");
      });
    }

    /**
     * 拒绝
     */
    $scope.reject = function () {
      var popup = $ionicPopup.show({
        template: '<textarea rows="5" style="overflow:hidden;resize:none;" ng-model="project.engineerReason" placeholder="请填写拒绝理由"></textarea>',
        scope: $scope,
        buttons: [
          {
            text: "提交",
            type: "button-positive",
            onTap: function (e) {
              e.preventDefault();
              if($scope.project.engineerReason == ""){
                return;
              }
              if (!angular.isUndefined($scope.project.engineerReason) || $scope.project.engineerReason != ""){
                // 判断是否为空 否提交
                rejectOrAgree(user.userId, $scope.project.projectId, "N", $scope.project.engineerReason, popup);
                $ionicHistory.goBack();
                $task.getCountOfTasks(user.userId);
                $rootScope.listStatus = "IS_CHECK";
              }
            }
          },
          {
            text: "取消",
            type: "button-stable gray-bg"
          }
        ]
      });
    }

    /**
     * 同意
     */
    $scope.agree = function () {
      $cordovaDialogs.confirm("是否同意？","同意审批",["否","是"]).then(function (buttonIndex) {
        if (buttonIndex == 2){
          rejectOrAgree(user.userId, $scope.project.projectId, "Y", "", undefined);
        }
      });
    }

    /**
     * 拒绝或同意
     * @param userId
     * @param projectId
     * @param engineerStatus
     * @param engineerReason
     * @param popup
     */
    function rejectOrAgree(userId, projectId, engineerStatus, engineerReason, popup) {
      $dfHttp.post("api/others/approveEngineerChange.json", {
        userId: userId,
        projectId: projectId,
        engineerStatus: engineerStatus,
        engineerReason: engineerReason
      }).success(function (data) {
        $log.debug(data);
        if (data.code == "SUCCESS"){
          $loading.showSuccess("更改状态成功");
          if (!angular.isUndefined(popup)){
            popup.close();
          }
          $ionicHistory.goBack();
          $task.getCountOfTasks(user.userId);
          $rootScope.listStatus = "IS_CHECK";
        } else{
          $loading.showError("更改状态失败");
        }
      }).error(function (e) {
        $loading.showError("服务器有点小问题，请稍后再试");
      });
    }

    /**
     * 选择图片
     * @param type
     */
    $scope.goPhoto = function (index, imageId, type, isDisabled) {
      checkImageId = imageId;
      var imagesCache = $imageUploadCache.getImagesByParams(imageId, 'GCLBG', 'GLBG');

      if (!flag){
        imagesCache.images = imagesClass[imageId-1];
      } else{
        // imagesCache.images = imagesClass[imageId-1];
        if (!imagesCache.images){
          imagesCache.images = imagesClass[imageId-1];
        }
      }

      angular.forEach(imagesClass[imageId-1], function (o, i) {
        if (imagesCache.images[i]) {
          imagesCache.images[i].imageUrl = o.middleImageUrl;
        }
      })

      flag = true;

      $state.go('tab.task-common-photo', {
        "args": {
          "funId": imageId,
          "funName": "GCLBG",
          "imageClass": type,
          "netImages": imagesCache.images
        },"disable": isDisabled
      });
    }

    $scope.$on("$stateChangeSuccess", function () {
      angular.forEach($scope.spmsEngineerChangeList, function (obj, index) {
        if (checkImageId == obj.imageId){
          obj.GLBG = $imageUploadCache.getImagesCount(obj.imageId, "GCLBG", "GLBG") > 0 || (imagesClass[obj.imageId-1] && imagesClass[obj.imageId-1].length > 0) ? "HAS_IMAGE" : "";
        }
      })
    })

    function imageUpload(ary) {
      //从缓存中获取图片url,并从文件读取图片。
      angular.forEach(ary, function (obj, index) {
        var imageCache = $imageUploadCache.getImagesByParams(obj.imageId, 'GCLBG', 'GLBG');

        if (!imageCache.images) {
          imageCache.images = [];
        }

        var imageCacheCount = imageCache.images.length;
        var photoDatasArray = [];

        angular.forEach(imageCache.images, function (image) {
          var pickImage = image.imageUrl;
          if (image.resource == 'NETWORK') {
            imageCacheCount--;
            return;
          }
          var lastIndexOfSlash = pickImage.lastIndexOf('/');
          var filePath = pickImage.substr(0, lastIndexOfSlash); //p
          var fileName = pickImage.substr(lastIndexOfSlash + 1, pickImage.length);

          $cordovaFile.readAsArrayBuffer(filePath, fileName).then(function (arrayBuffer) {
            var base64String = $dfUtil.arrayBufferToBase64(arrayBuffer);
            photoDatasArray.push(base64String);
          }, function (error) {
            $loading.showError("本地图片没有找到,请确认存在");
          })
        })

        $loading.show("图片提交中");
        var timer = $interval(function (e) {
          if (photoDatasArray.length == imageCacheCount) {
            if (photoDatasArray.length > 0){
              $interval.cancel(timer);
              $task.uploadImage("GCLBG", obj.engineerId, imageCache.imageClass, imageCache.invalidUuids, photoDatasArray)
                .success(function (data) {
                  // $task.uploadImage("PROJECT", 5621, imageCache.imageClass, imageCache.invalidUuids, photoDatasArray).success(function (data) {
                  if (data.code == "SUCCESS") {
                    $loading.showSuccess("上传图片成功");
                  } else {
                    $loading.showError(data.msg);
                  }
                }).error(function (error) {
                $loading.showError("网络异常,请稍后再试");
              })
            }
          }
          // else {
          //   $loading.showError("网络异常,请稍后再试");
          // }
        }, 200, 10);
      })
    }
  })

